package com.jeesite.modules.file.service;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jms.Queue;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.BucketInfo;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.jeesite.common.collect.MapUtils;
import com.jeesite.common.idgen.IdGenerate;
import com.jeesite.common.io.FileUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.conf.BeanConfig;
import com.jeesite.modules.conf.ConfigData;
import com.jeesite.modules.file.entity.FileEntity;
import com.jeesite.modules.file.entity.FileUpload;
import com.jeesite.modules.file.entity.FileUploadParams;
import com.jeesite.modules.file.service.support.FileUploadServiceExtendSupport;

@Service
public class FileUploadServiceExtendImpl extends FileUploadServiceExtendSupport {
	private static  Logger logger=LoggerFactory.getLogger(FileUploadServiceExtendImpl.class);
    private static String endpoint="https://oss-cn-beijing.aliyuncs.com";
    private static String accessKeyId="LTAI4FfopRNCz7zsnSX8GeVV";
    private static String accessKeySecret ="nIAiglN19gtgmdBlsLcqUZekuJgStY";
    private static String bucketName = "bjhylfkj";
    private static String firstKey = "knowing";
    private static String serverUrl="https://bjhylfkj.oss-cn-beijing.aliyuncs.com";
    @Autowired
    private ConfigData configData;
    @Autowired
    private Queue queue;
    @Autowired
    private Queue uploadQueue;
    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;
    @Autowired
    private ThreadPoolTaskExecutor defaultThreadPool;
    @Override
    @Async("defaultThreadPool")
    public String getFileUrl(FileUpload fileUpload) {
    	String fileUrl = super.getFileUrl(fileUpload);
    	final String fileUrlw2=serverUrl+"/knowing"+fileUrl;
    	defaultThreadPool.submit(()->{
    		String projectPath = FileUtils.getWebappPath();
//    		String project=FileUtils.getProjectPath();
//    		String tempPath=FileUtils.getTempDirectoryPath();
//    		String userPath=FileUtils.getUserDirectoryPath();
    		jmsMessagingTemplate.convertAndSend(uploadQueue, projectPath+fileUrl);
    	});
//    	String fileName = fileUpload.getFileName();
//    	File file = FileUtils.getFile(fileUrl);
//    	boolean exists = file.exists();
    	return fileUrlw2;
//    	return super.getFileUrl(fileUpload);
    }
    @Override
	public void uploadFile(FileEntity fileEntity) {
         super.uploadFile(fileEntity);
	}
    @Override
    public Map<String, Object> uploadFile(FileEntity fileEntity, FileUploadParams params) {
    	return super.uploadFile(fileEntity, params);
    }
    @Override
    public void saveUploadFile(FileUpload fileUpload) {
//    	System.out.println("保存文件");
//    	FileEntity fileEntity=fileUpload.getFileEntity();
//    	String path=fileEntity.getFileRealPath();
//    	String name=fileUpload.getFileName();
//    	File file=new File(path);
//		try {
//			URL doUploadFile = doUploadFile(fileEntity);
//			String pathUrl=doUploadFile.toURI().toString();
//			fileUpload.getFileEntity().setFilePath(pathUrl);
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		} catch (URISyntaxException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
    	super.saveUploadFile(fileUpload);
    }
    @Override
    public String downFile(FileUpload fileUpload, HttpServletRequest request, HttpServletResponse response) {
    	return super.downFile(fileUpload, request, response);
    }
	@Override
	public boolean fileExists(FileEntity fileEntity) {
//		String path=fileEntity.getFileRealPath();
//		File localFile = new File(path);
//		return localFile.exists();
		return super.fileExists(fileEntity);
	}
	
    /**
     * 查看BucketInfo
     */
    public void getBucketInfo(){
    	OSS ossClient=new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
    	BucketInfo info=ossClient.getBucketInfo(bucketName);
		logger.debug("Bucket " + bucketName + "的信息如下：");
		logger.debug("\t数据中心：" + info.getBucket().getLocation());
		logger.debug("\t创建时间：" + info.getBucket().getCreationDate());
		logger.debug("\t用户标志：" + info.getBucket().getOwner());
    }
    /**
     * 存入字符串
     */
    public void putStr(String str){
    	OSS ossClient=new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
    	//存入字符串到OSS
		InputStream is = new ByteArrayInputStream(str.getBytes());
        ossClient.putObject(bucketName, firstKey, is);
        logger.debug("Object：" + firstKey + "存入OSS成功。");
    }
    /**
     * 下载
     * @throws IOException 
     */
    public void getOject() throws IOException{
    	OSS ossClient=new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
    	//下载文件
        OSSObject ossObject = ossClient.getObject(bucketName, firstKey);
        InputStream inputStream = ossObject.getObjectContent();
        StringBuilder objectContent = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        while (true) {
            String line = reader.readLine();
            if (line == null)
                break;
            objectContent.append(line);
        }
        inputStream.close();
    }
	
	/**
	 * 上传文件，首次上传文件都调用（保存到文件实体表之前调用）
	 * @param fileEntity 文件实体信息
	 * @param fileEntity.getFileRealPath() 文件实际磁盘路径
	 * @exception 支持抛出 throw ServiceException("文件不符合要求") v4.1.5
	 */
	
//	/knowing/userfiles/fileupload/202003/1238799276055363586.mp4
	public URL doUploadFile(FileEntity fileEntity) throws IOException, URISyntaxException {
		String folder=firstKey+"/"+new SimpleDateFormat("yyyyMMdd").format(new Date());
		OSS ossClient=new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);
		List<String> result=new ArrayList<String>();
		String realPath=fileEntity.getFileRealPath();
		
		File file = new File(realPath);
		URL url=null;
        		
		InputStream is=new FileInputStream(file);
	    String path=file.getName();
	    String type=path.substring(path.lastIndexOf("."));
	    String fileNameNew=IdGenerate.randomLong()+type;
		Long fileSize=file.length();  
		ObjectMetadata metadata=new ObjectMetadata();
		metadata.setContentLength(is.available());
		metadata.setCacheControl("no-cache");
		metadata.setHeader("Pragma","no-cache");
		metadata.setContentDisposition("filename/filesize="+fileNameNew+"/"+fileSize+"Byte.");
		PutObjectResult putResult=ossClient.putObject(bucketName,folder+"/"+fileNameNew,is,metadata);
		url=getUrl(ossClient,folder+"/"+fileNameNew);
		ossClient.shutdown();
		return url;
	}
	private static URL getUrl(OSS ossClient, String key) {
        // 设置URL过期时间为100年
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 100);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        return url;
    }
}
